/*导航栏右侧用户信息*/
import { defineStore } from 'pinia'
import {apiUser} from "@/api/user"
import { type UserState } from '@/types/index'

export const useUserStore = defineStore('user',{
    state: (): UserState => ({
        id:'',
        userType:0,
        name: '未登录',
        avatar: '/img/avatar/not_login.svg',
        mobile: '',
        sex: 1,// 1男0女
        // roles: [],
        // perms: []
        //以上默认值为游客
    }),
    actions:{
        async RESET_STATE() {
            this.$reset()
        },
        getUserInfo(){
            return new Promise((resolve, reject) => {
                apiUser.getUserInfo().then((res:any)=>{
                    const json = res.data
                    this.id = json.id
                    this.userType = json.userType
                    this.name = json.name
                    this.sex = json.sex
                    this.avatar = '/img/avatar/face_'+json.sex+'.svg'
                    if(json.mobile)   this.mobile = json.mobile
                    resolve(res.data)
                }).catch((error:any) => {
                    reject(error)
                })
            })
        },
        /**
         * 清除 Token ,需根据项目实际情况改写
         */
        resetToken() {
            localStorage.removeItem(import.meta.env.VITE_TOKEN_KEY)
            this.RESET_STATE().then(()=>{})
        },
        /**
         *  退出登录
         */
        logout() {
            return new Promise((resolve, reject) => {
                apiUser.logout().then(() => {
                    localStorage.removeItem(import.meta.env.VITE_TOKEN_KEY)
                    this.resetToken()
                    resolve(null)
                }).catch((error:any) => {
                    reject(error);
                });
            });
        },
        /**
         * 设置 Token ,需根据项目实际情况改写
         */
        setToken(val:string) {
            localStorage.setItem(import.meta.env.VITE_TOKEN_KEY,val)
        },
        /**
         * 读取已存在的 Token ,需根据项目实际情况改写
         */
        getToken() {
            return localStorage.getItem(import.meta.env.VITE_TOKEN_KEY)
        },
    },
})